package com.pdx.service.impl;

import com.pdx.entity.SysUser;
import com.pdx.entity.SysUserRole;
import com.pdx.entity.vo.UserOwnRoleVo;
import com.pdx.exception.BusinessException;
import com.pdx.exception.code.BaseResponseCode;
import com.pdx.mapper.SysUserRoleMapper;
import com.pdx.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author PDX
 * @website https://blog.csdn.net/Gaowumao
 * @Date 2022-05-02 13:24
 * @Description
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 根据用户ID查询出与其对应的所有角色id的列表
     * @param id
     * @return
     */
    @Override
    public List<String> getRoleIdsByUserId(String id) {
        List<String> list = userRoleMapper.getRoleIdsByUserId(id);
        return list;
    }

    @Override
    public void addUserRoleInfo(UserOwnRoleVo vo) {
        //先删除它们之间的关联数据
        userRoleMapper.removeRoleByUserId(vo.getUserId());
        //如果用户所对应的角色为空
        if (vo.getRoleIds() == null || vo.getRoleIds().isEmpty()){
            return;
        }
        List<SysUserRole> list = new ArrayList<>();
        for (String roleId : vo.getRoleIds()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setId(UUID.randomUUID().toString());
            sysUserRole.setUserId(vo.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRole.setCreateTime(new Date());
            list.add(sysUserRole);
        }
        int i = userRoleMapper.batchInsertUserRole(list);
        if (i == 0){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }
}
